# 导入必要的库和模块
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import joblib

# 加载数字数据集（MNIST 28x28）
mnist = fetch_openml('mnist_784', version=1, as_frame=False)
X, y = mnist.data, mnist.target.astype(int)

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 1
best_knn = None

# 初始化一个列表以存储每个k值的准确率
accuracies = []

# 尝试从1到10的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
for k in range(1, 11):  # MNIST数据集较大，k不建议太大
    knn = KNeighborsClassifier(n_neighbors=k, n_jobs=-1)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    acc = accuracy_score(y_test, y_pred)
    accuracies.append(acc)
    if acc > best_accuracy:
        best_accuracy = acc
        best_k = k
        best_knn = knn

# 将最佳KNN模型保存到二进制文件
joblib.dump(best_knn, "knn_model.pkl")

# 打印最佳准确率和相应的k值
print(f"最佳准确率: {best_accuracy:.4f}, 最佳k值: {best_k}")